package com.demo.service_admin.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaBuilder.In;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import com.demo.dao_admin.CourseSectionDAO;
import com.demo.entity.Course;
import com.demo.entity.CourseSection;
import com.demo.service_admin.CourseSectionService;

@Service("adminCourseSectionService")
@Transactional
public class CourseSectionServiceImpl implements CourseSectionService {

	@Resource(name = "adminCourseSectionDAO")
	CourseSectionDAO courseSectionDAO;

	@Override
	public Page<CourseSection> findAll(CourseSection courseSection, Pageable pageable) {
		

		Specification<CourseSection> spec = new Specification<CourseSection>() {
			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<CourseSection> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				//Please tell me：下面会翻译成什么sql
				//两张表的内联或者做外联查询
				// from 章节表 inner join 课程表 where 课程表.id=?1 and 章节表.chapter=?2
				Join<CourseSection, Course> join = root.join("course", JoinType.INNER);// A left outer join B 不等于 B left outer join A
				
				List<Predicate> predicates = new ArrayList<>();
				
				predicates.add(cb.equal(join.get("id"), courseSection.getCourse().getId()));
				if(StringUtils.isNotEmpty(courseSection.getChapter())) {
					predicates.add(cb.like(root.get("chapter"), "%" + courseSection.getChapter() + "%"));
				}
				return cb.and(predicates.toArray(new Predicate[predicates.size()]));// 把所有查询条件用and拼接
				
			}
		};

		Page<CourseSection> list = courseSectionDAO.findAll(spec, pageable);
		return list;
	}

	@Override
	public CourseSection findById(Long id) {
		CourseSection courseSection = courseSectionDAO.findById(id).get();
		return courseSection;
	}
	
	@Override
	public int batchDelete(Long[] ids) {
		return courseSectionDAO.batchDelete(ids);
	}
	
	/**
	 * Specification使用in查询，建议在DAO接口层使用hql语句更方便！！
	 * List<Predicate> predicates = new ArrayList<>();
				In<String> in = cb.in(root.get("id"));
				for(String id:ids) {
					in.value(id);
				}
				predicates.add(in);
	 */
}